<template>
  <!-- <ContentWrap> -->
  <el-row>
    <el-col v-for="(item, index) in workstationDataList" :key="`workstation-${index}`" :xl="4" :lg="4" :md="6" :sm="6" :xs="12">
      <el-card shadow="hover" class="mr-5px mt-5px mb-5px">
        <div class="flex">
          <div class="mr-16px align-top">
            <img src="@/assets/imgs/receipt.jpg" alt="" class="index-img"/>
          </div>
          <div v-if="item.label == '未完成'" @click="gotoInternalDetail(2, item)">
            <div class="text-20px">{{ item.label }}</div>
            <div class="mt-10px text-14px text-gray-500">
              {{ item.value }}
            </div>
          </div>
          <div v-if="item.label != '未完成' && item.label != '总数'" @click="gotoInternalDetail(1, item)">
            <div class="text-20px">{{ item.label }}</div>
            <div class="mt-10px text-14px text-gray-500">
              {{ item.value }}
            </div>
          </div>
          <div v-if="item.label == '总数'">
            <div class="text-20px">{{ item.label }}</div>
            <div class="mt-10px text-14px text-gray-500">
              {{ item.value }}
            </div>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>

  <ContentWrap>
    <el-table v-loading="loading" :data="list" ref="reportTable">
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="规格型号" align="center" prop="flex" />
      <el-table-column label="长度" align="center" prop="len" />
      <el-table-column label="内码" align="center" prop="internalCode" />
      <el-table-column label="工位" align="center" prop="workstationName" />
      <el-table-column label="数值" align="center" prop="workstationValue" />
      <el-table-column label="操作时间" align="center" prop="operatorTime" />
    </el-table>
  </ContentWrap>
</template>

<style lang="scss" scoped>
.el-card__body {
  padding: 0 !important;
}
.index-img {
  width: 50px;
  height: 50px;
  vertical-align: top;
}
</style>

<script lang="ts" setup>

import { useUserStore } from '@/store/modules/user'
import * as homeApi from '@/api/hcxly/home/Index'
import router from "@/router";
import download from "@/utils/download";
import { getAccessToken } from '@/utils/auth'
import {useCache} from "@/hooks/web/useCache";
defineOptions({ name: 'home' })
const userStore = useUserStore()
const loading = ref(false)
const message = useMessage() // 消息弹窗

const workstationQueryParams = reactive({
  cacheOrderCode: null,
  deptId : userStore.getUser.deptId
})

const workstationDataList = ref([]) // 列表的数据
const getList = async () => {
  loading.value = true
  try {
    workstationDataList.value = await homeApi.listCurrentUserWorkstationOrderInfo(workstationQueryParams.deptId, workstationQueryParams.cacheOrderCode);
  }finally {
    loading.value = false
  }
}

const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const cacheOrderList = ref([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined,
  name: undefined,
  orderDetailId: undefined,
  orderType: "home",
  cacheOrderCode: undefined
})


/** 查询实时生产列表 */
const getList3 = async () => {
  loading.value = true

  try {
    const data = await homeApi.listCurrentWorkstationDetail(queryParams)
    list.value = data.list
  } finally {
    loading.value = false
  }
}

const list2 = ref([])
const queryParams2 = reactive({
  pageNo: 1,
  pageSize: 10,
  code: '',
  cacheOrderCode: null
})
/** 查询扫码溯源 */
const getList2 = async () => {
  console.log(queryParams2)
  loading.value = true
  try {
    list2.value = await homeApi.getCodeRetrospect(queryParams2)
  } finally {
    loading.value = false
  }
}

// 响应式数据
const isConnected = ref(false);
const messages = ref([]);
const messageInput = ref('');

const wsUrl = ref(import.meta.env.VITE_BASE_URL.replace("http", "ws") + '/websocket'); // 使用公共WebSocket测试服务器
const socket = ref(null);
const lastActivity = ref('无');
const isFetching = ref(false);
const nextUpdateTime = ref(null);
const fetchInterval = ref(null);

// 方法
const connect = () => {
  try {
    const token = "Authorization=Bearer " + getAccessToken();
    socket.value = new WebSocket(wsUrl.value + '?token=' + encodeURIComponent(token));

    socket.value.onopen = () => {
      isConnected.value = true;

      fetchData();
      console.log('成功连接到WebSocket服务器');

      // 启动定时器，每30秒获取一次数据
      startFetchInterval();
    };

    socket.value.onmessage = (event) => {
      let data = event.data;
      handleMessage(data);
    };

    socket.value.onerror = (error) => {
      console.error('WebSocket错误:', error);
    };

    socket.value.onclose = () => {
      isConnected.value = false;
      console.log('WebSocket连接已关闭');
    };
  } catch (error) {
    console.error('连接失败:', error);
  }
};

const disconnect = () => {
  if (socket.value) {
    socket.value.close();
  }
};

const sendMessage = () => {
  if (messageInput.value.trim() && isConnected.value) {
    socket.value.send(messageInput.value);
    messageInput.value = '';
  }
};

const fetchData = () => {
  if (isConnected.value && socket.value.readyState === WebSocket.OPEN) {
    isFetching.value = true;

    const request = {
      deptId: workstationQueryParams.deptId,
      cacheOrderCode: workstationQueryParams.cacheOrderCode,
      pageNo: 1,
      pageSize: 10,
      id: queryParams.id,
      name: queryParams.name,
      orderDetailId: queryParams.orderDetailId,
      orderType: queryParams.orderType,
      token: getAccessToken()
    };

    socket.value.send(JSON.stringify(request));

    // 设置下一次更新时间（30秒后）
    nextUpdateTime.value = new Date().getTime() + 5000;
  }
};

const startFetchInterval = () => {
  // 先清除可能存在的旧定时器
  stopFetchInterval();

  // 每30秒获取一次数据
  fetchInterval.value = setInterval(() => {
    if (isConnected.value) {
      fetchData();
    }
  }, 5000);
};

const stopFetchInterval = () => {
  if (fetchInterval.value) {
    clearInterval(fetchInterval.value);
    fetchInterval.value = null;
  }
};

const handleMessage = (response) => {
  isFetching.value = false;
  const message = JSON.parse(response);
  workstationDataList.value = message.currentUserWorkstationOrderInfo.data;
  list.value = message.currentWorkstationDetail.data.list;
};


const reportTable = ref()


const gotoInternalDetail = (type, item) => {
  if(type == 1){
    router.push({
      name: 'productionScheduleReport3',
      query: {
        cacheOrderCode: queryParams2.cacheOrderCode,
        labelType: item.labelType,
        labelTypeValue: item.labelTypeValue
      }
    })
  }else {
    router.push({
      name: 'unfinishReport',
      query: {
        finishStatus: 'unfinish',
        cacheOrderCode: queryParams2.cacheOrderCode
      }
    })
  }
}

const handleQuery = () => {
  getList2();
}

const exportWord = async () => {
  try {
    await message.exportConfirm();
    loading.value = true
    const data = await homeApi.exportWord(queryParams2);
    download.excel(data, '追溯报告.txt');
  }catch {

  } finally {
    loading.value = false
  }
}

if (onUnmounted) {
  onUnmounted(() => {
    // 组件卸载时断开连接
    if (socket.value) {
      socket.value.close();
    }
  });
}

/** 初始化 **/
onMounted(() => {
  //getList()
  //getList3()

  connect();
})

</script>
